<script lang='ts'  setup>
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router';
import api from '@/api'
import storage from '@/utils/storage';
import userStore from '@/store/user'
import md5 from 'md5'
const router = useRouter()



const loginForm = reactive({
    username: 'admin',
    password: 'admin'
})
const loginFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '用户名称是必填的', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入登陆密码', trigger: 'blur' },
        { min: 5, message: '密码长度最少为5位', trigger: 'blur' }
    ]
})

const handleLogin = async () => {
    loginForm.password = md5(loginForm.password)
    const { data: res } = await api.login({ userName: loginForm.username, userPwd: loginForm.password })
    if (res) {
        storage.set('userInfo', res)
        userStore.getUserInfo()
        router.replace(storage.getState('currentMenu') || '/home')
    }
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            handleLogin()
        }
    })
}
</script>

<template>
    <div id='Login' class="flex justify-center items-center cover ">
        <div class="flex flex-col   card w-[500px] h-[300px] py-[15px] ">
            <h1 class=" text-[30px] select-none text-center">后台登陆</h1>
            <el-form size="large" class="flex-1 px-[60px]" :model="loginForm" :rules="rules" ref="loginFormRef">
                <el-form-item class=" mt-[20px]" prop="username">
                    <el-input v-model.trim="loginForm.username" placeholder="请输入用户名称" clearable autocomplete
                        name="userName" prefix-icon="UserFilled">
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input type="password" v-model.trim="loginForm.password" show-password placeholder="请输入登陆密码"
                        name="userPwd" autocomplete prefix-icon="Lock">
                    </el-input>
                </el-form-item>
                <el-form-item class="mt-[40px] " label-width="1">
                    <el-button type="primary" round class="w-[80%]" @click="submitForm(loginFormRef)">Login</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<style>
#Login {
    background: linear-gradient(-45deg, #eca691, #b35d7e, #5097b0, #42ac93);
    background-size: 400% 400%;
    animation: gradient 15s ease infinite;
    height: 100vh;
}

@keyframes gradient {
    0% {
        background-position: 0% 50%;
    }

    50% {
        background-position: 100% 50%;
    }

    100% {
        background-position: 0% 50%;
    }
}

.el-form-item__content {
    justify-content: center;
}
</style>